package com.geek.factory.controller;

import com.geek.factory.constant.SuccessConstant;
import com.geek.factory.dto.DeviceRepairRecordDTO;
import com.geek.factory.dto.RepairSubmitDTO;
import com.geek.factory.entity.DeviceRepairRecord;
import com.geek.factory.entity.DeviceRepairReport;
import com.geek.factory.result.Result;
import com.geek.factory.service.DeviceRepairRecordService;
import com.geek.factory.service.DeviceRepairReportService;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/repair/record")
public class DeviceRepairRecordController {

    @Autowired
    private DeviceRepairRecordService recordService;

    @Autowired
    private DeviceRepairReportService reportService;

    @PostMapping("/complete")
    public Result completeRepair(@RequestBody RepairSubmitDTO dto) {
        // 1. 查询对应的报修单
        DeviceRepairReport report = reportService.getById(dto.getReportId());
        if (report == null) {
            return new Result(SuccessConstant.FAIL, "报修单不存在");
        }

        // 2. 状态校验
        if (!"approved".equalsIgnoreCase(report.getStatus())) {
            return new Result(SuccessConstant.FAIL, "当前报修单状态不允许维修");
        }

        // 3. 构建维修记录
        DeviceRepairRecord record = new DeviceRepairRecord();
        record.setReportId(dto.getReportId());
        record.setRepairer(dto.getRepairer());
        record.setRepairContent(dto.getRepairContent());
        record.setRepairTime(LocalDateTime.now());
        record.setIsCompleted(true);

        boolean saved = recordService.save(record);
        boolean updated = reportService.updateStatus(dto.getReportId(), "repaired");

        return (saved && updated)
                ? new Result(SuccessConstant.SUCCESS, "维修完成")
                : new Result(SuccessConstant.FAIL, "维修失败");
    }


    /**
     * 查询所有维修记录（含设备与产线信息）
     */
    @GetMapping("/list")
    public Result list() {
        List<DeviceRepairRecordDTO> list = recordService.getRecordListWithDetails();
        return new Result(SuccessConstant.SUCCESS, "查询成功", list);
    }

    /**
     * 根据 ID 查询单条记录
     */
    @GetMapping("/{id}")
    public Result getById(@PathVariable Long id) {
        DeviceRepairRecord record = recordService.getById(id);
        return record != null
                ? new Result(SuccessConstant.SUCCESS, "查询成功", record)
                : new Result(SuccessConstant.FAIL, "记录不存在");
    }

    /**
     * 新增维修记录
     */
    @PostMapping("/add")
    public Result add(@RequestBody DeviceRepairRecord record) {
        boolean saved = recordService.save(record);
        return saved
                ? new Result(SuccessConstant.SUCCESS, "新增成功")
                : new Result(SuccessConstant.FAIL, "新增失败");
    }

    /**
     * 更新维修记录
     */
    @PutMapping("/update")
    public Result update(@RequestBody DeviceRepairRecord record) {
        boolean updated = recordService.updateById(record);
        return updated
                ? new Result(SuccessConstant.SUCCESS, "更新成功")
                : new Result(SuccessConstant.FAIL, "更新失败");
    }

    /**
     * 删除维修记录
     */
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Long id) {
        boolean deleted = recordService.removeById(id);
        return deleted
                ? new Result(SuccessConstant.SUCCESS, "删除成功")
                : new Result(SuccessConstant.FAIL, "删除失败");
    }


    @GetMapping("/export")
    public void exportToExcel(HttpServletResponse response) throws IOException {
        List<DeviceRepairRecordDTO> records = recordService.getRecordListWithDetails();

        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("维修记录");

        // 表头
        String[] headers = {
                "ID", "报修单ID", "维修人", "维修内容", "维修时间", "是否完成",
                "设备名称", "设备类型", "产线名称"
        };

        XSSFRow headerRow = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            headerRow.createCell(i).setCellValue(headers[i]);
        }

        // 数据
        for (int i = 0; i < records.size(); i++) {
            DeviceRepairRecordDTO r = records.get(i);
            XSSFRow row = sheet.createRow(i + 1);
            row.createCell(0).setCellValue(r.getId());
            row.createCell(1).setCellValue(r.getReportId());
            row.createCell(2).setCellValue(r.getRepairer());
            row.createCell(3).setCellValue(r.getRepairContent());
            row.createCell(4).setCellValue(r.getRepairTime() != null ? r.getRepairTime().toString() : "");
            row.createCell(5).setCellValue(Boolean.TRUE.equals(r.getIsCompleted()) ? "是" : "否");
            row.createCell(6).setCellValue(r.getDeviceName());
            row.createCell(7).setCellValue(r.getDeviceType());
            row.createCell(8).setCellValue(r.getLineName());
        }
        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment;filename=repair_records.xlsx");
        response.setCharacterEncoding("UTF-8");

        // 输出
        ServletOutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        outputStream.flush();
        outputStream.close();
        workbook.close();
    }
}
